<?php
require_once 'ApibaseController.php';

/**
 * 検索条件で問い合わせAPI<br />
 *
 * 検索条件で問い合わせAPI
 *
 * @package apamanshop
 * @author ushijima
 * @copyright コピーライト(要確認)
 */
class Inquiry_ApiconditionsController extends Inquiry_ApibaseController
{
    // ====================定数====================
    /**
     * キャンペーン区切り文字
     */
    const DELIM_CAMPAIGN = ";";

    /**
     * お宝区切り文字
     */
    const DELIM_OTAKARA = ",";

    // 店舗情報
    private $shoplist = array();

    /**
     * モバイル区分
     */
    private $m_isMobile;

    private $m_strMobileKbn;

    /**
     * 利用ｻｲﾄ区分
     */
    private $m_strUseKbn;

    /**
     * キャリア
     */
    private $m_carrier;

    /**
     * あげちゃいますキャンペーン(全て)(Key:キャンペーンコード Value:キャンペーン情報)
     */
    private $m_arrCampaignAgechauAll;

    /**
     * あげちゃいますキャンペーン(Key:キャンペーンコード Value:キャンペーン情報)
     */
    private $m_arrCampaignAgechau;

    /**
     * あげちゃいますキャンペーンお宝(Key:キャンペーンコード Value:お宝情報リスト)
     */
    private $m_arrCampaignAgechauTakara;

    /**
     * 部屋付きキャンペーン（反響カウント用）
     */
    private $m_arrCampaignHeya;

    /**
     * 部屋付きキャンペーン（メールタイトル用）(Key:キャンペーンコード Value:キャンペーン情報)
     */
    private $m_arrCampaignHeyaList;

    /**
     * W75LETTERS_CAMPAIGN 登録/更新件数
     */
    private $m_insupdW75LettersCampaignCnt;

    /**
     * W76APPLY_CAMPAIGN 登録件数
     */
    private $m_insW76ApplyCampaignCnt;

    /**
     * W25CAMPAIGN_DOWNLOAD_MNG 登録件数
     */
    private $m_insW25CampaignDownloadMngCnt;

    /**
     * 問い合わせID
     */
    private $m_strToiawaseId;

    /**
     * 検索条件で問合せAPIアクション
     *
     * @access public
     * @return void
     */
    public function indexAction()
    {
        // 変数初期化処理 start

        // 20141223 S_Add
        // 検索区分
        $strSrhType = $this->_params['SrhType']; // 地域：1　路線・駅：2　店舗：3

        $strKindname = $this->_params['kindname']; // kindごとの名称
        $strkindnameValue = $this->_params['kindnameValue']; // kindごとの名称　表示
        $strKindcode = $this->_params['kindcode']; // kindごとのコード

        $strP_shopcds = $this->_params['p_shopcds']; // 店舗コード
        $strP_shopnames = $this->_params['p_shopnames']; // 店舗名称
        $strTinryo1 = $this->_params['tinryo1']; // 賃料min　DB
        $strTinryo2 = $this->_params['tinryo2']; // 賃料max　DB

        // ==賃料（下限）
        $strTinryo1 = $strTinryo1 * 10000;
        $i = 0;
        $iYachinMin = 1;
        foreach (Apm_Config_Search::$KENSAKU_CHINRYO_MIN as $key => $val)
        {
            if ($strTinryo1 == $key)
            {
                $iYachinMin = $i + 1;
                break;
            }
            $i++;
        }
        $strTinryo1 = $iYachinMin;
        // ==賃料（上限）
        if ($strTinryo2 == "999")
        {
            $strTinryo2 = 27;
        }
        else
        {
            $strTinryo2 = $strTinryo2 * 10000;
            $i = 0;
            $iYachinMax = 30;
            foreach (Apm_Config_Search::$KENSAKU_CHINRYO_MAX as $key => $val)
            {
                if ($strTinryo2 == $key)
                {
                    $iYachinMax = $i + 1;
                    break;
                }
                $i++;
            }
            $strTinryo2 = $iYachinMax;
        }

        $strTinryo1Value = $this->_params['tinryo1Value']; // 賃料min　表示
        $strTinryo2Value = $this->_params['tinryo2Value']; // 賃料max　表示
        $strTinryo_jouken2 = $this->_params['tinryo_jouken2']; // 管理費・共益費含む　DB
        $strTyusyajyo_komi = $this->_params['tyusyajyo_komi']; // 管理費・共益費含む　DB
        $strShikikin_nashi = $this->_params['shikikin_nashi']; // 敷金ゼロ　DB
        $strReikin_nashi = $this->_params['reikin_nashi']; // 礼金ゼロ　DB
        $strTinryoNotesValue = $this->_params['tinryoNotesValue']; // 賃料備考　表示
        $strSyubetuValue = $this->_params['syubetuValue']; // 建物種別　表示
        $strSyubetuDB = $this->_params['syubetuDB']; // 建物種別　DB
        $strEkitoho = $this->_params['ekitoho']; // 駅徒歩　DB
        $strBas_riyou = $this->_params['bas_riyou']; // バス利用含む　DB
        $strEkitohoValue = $this->_params['ekitohoValue']; // 駅徒歩　表示
        $strSenyu1 = $this->_params['senyu1']; // 専有面積min　DB
        $strSenyu2 = $this->_params['senyu2']; // 専有面積max　DB
        if (is_numeric($strSenyu2))
        {
            $strSenyu2 = "" . intVal($strSenyu2) - 1;
        }
        $strSenyu1Value = $this->_params['senyu1Value']; // 専有面積min　表示
        $strSenyu2Value = $this->_params['senyu2Value']; // 専有面積max　表示
        $strMadoriValue = $this->_params['madoriValue']; // 間取り　表示
        $strMadoriDB = $this->_params['madoriDB']; // 間取り　DB
        $strBuilt = $this->_params['built']; // 築年数　DB
        $strBuiltValue = $this->_params['builtValue']; // 築年数　表示
        $strKodawariTypeDB = $this->_params['kodawariTypeDB']; // こだわり条件　DB
        $strKodawariDB = $this->_params['kodawariDB']; // 人気のこだわり条件　DB
        $strOtherNotesValue = $this->_params['otherNotesValue']; // その他　表示
        $strTimeStr = $this->_params['TimeStr'];
        // 20141223 E_Add

        $cntctWayFax = $this->_params['CntctWayFax'];
        $cntctWayMail = $this->_params['CntctWayMail'];
        $cntctWayTel = $this->_params['CntctWayTel'];
        $inquiry1 = $this->_params['Inquiry1'];
        $inquiry2 = $this->_params['Inquiry2'];
        // $inquiry3 = $this->_params ['Inquiry3'];
        // $inquiry4 = $this->_params ['Inquiry4'];
        $raitenDate = $this->_params['RaitenDate'];
        $raitenTime = $this->_params['RaitenTime'];
        $this->m_strUseKbn = $this->_params['UseKbn'];
        $arrBukken['tenpoCd'] = $this->_params['ShopCd'];
        $mail = $this->_params['Mail'];
        $orgTatemonoCd = $this->_params['OrgTatemonoCd'];

        // モバイル区分・ジャンルコード
        $this->m_strMobileKbn = "";
        $this->m_carrier = "";
        $strLogGenruFlg = "";
        if (isset($this->_params['isMobile']) && !empty($this->_params['isMobile']))
        {
            $this->m_isMobile = $this->_params['isMobile'];
            $strLogGenruFlg = $this->_params['vintGenruFlg'];
            // iPhone、Android、スマホ用設定
            if ($strLogGenruFlg == '91' || $strLogGenruFlg == '92')
            {
                $this->m_isMobile = '2';
                $this->m_strUseKbn = "0";
                $this->m_carrier = "iPhone";
            }
            else if ($strLogGenruFlg == '93' || $strLogGenruFlg == '94')
            {
                $this->m_isMobile = '4';
                $this->m_strUseKbn = "0";
                $this->m_carrier = "Android";
            }
            else if ($strLogGenruFlg == '95' || $strLogGenruFlg == '96')
            {
                $this->m_isMobile = '3';
                $this->m_strUseKbn = "0";
                $this->m_carrier = "スマートフォン";
            }
            else if ($strLogGenruFlg == '105')
            {
                // スマホNifty用設定
                $this->m_isMobile = '3';
                $this->m_strUseKbn = '3';
                $this->m_carrier = "スマートフォン";
            }
            else if (empty($strLogGenruFlg))
            {
                $strLogGenruFlg = "1";
            }
            // モバイル用設定
            if ($this->m_isMobile == "1")
            {
                // 携帯Nifty用設定
                if ($strLogGenruFlg == '25' || $strLogGenruFlg == '26' || $strLogGenruFlg == '27')
                {
                    $this->m_strUseKbn = "3";
                }
                else
                {
                    $this->m_strUseKbn = "0";
                }
                // モバイル区分の判定
                if ($strLogGenruFlg == "1" || $strLogGenruFlg == "10" || $strLogGenruFlg == "25")
                {
                    // i-mode
                    $this->m_strMobileKbn = "1";
                    $this->m_carrier = "i-mode";
                }
                else if ($strLogGenruFlg == "2" || $strLogGenruFlg == "11" || $strLogGenruFlg == "26")
                {
                    // softbank
                    $this->m_strMobileKbn = "2";
                    $this->m_carrier = "SoftBank";
                }
                else if ($strLogGenruFlg == "3" || $strLogGenruFlg == "12" || $strLogGenruFlg == "27")
                {
                    // au
                    $this->m_strMobileKbn = "3";
                    $this->m_carrier = "EZweb";
                }
            }
        }
        else
        {
            $this->m_isMobile = "0";
            if ($this->m_strUseKbn == "1")
            {
                $strLogGenruFlg = "13";
            }
            else
            {
                $strLogGenruFlg = "0";
            }
        }
        $add_params['isMobile'] = $this->m_isMobile;
        $add_params['Carrier'] = $this->m_carrier;

        // 名前
        $name = $this->_params['NameSei'];
        if (!empty($this->_params['NameMei']))
        {
            $name .= "　" . $this->_params['NameMei'];
        }
        $add_params['Name'] = $name;

        // 20141130 S_Add
        // 名前(カナ)
        $nameKana = $this->_params['NameSeiKana'];
        if (!empty($this->_params['NameMeiKana']))
        {
            $nameKana .= "　" . $this->_params['NameMeiKana'];
        }
        $add_params['NameKana'] = $nameKana;
        // 20141130 E_Add

        // 希望時間
        $arrNeedTimeKbn = Array(
            "希望なし",
            "10時以前",
            "10時～12時",
            "12時～14時",
            "14時～16時",
            "16時～18時",
            "18時以降"
        );
        $add_params['strNeedTimeKbn'] = $arrNeedTimeKbn[$this->_params['NeedTimeKbn']];

        // 希望連絡手段
        $strCntctWayStr = "";
        $strCntctWayCd = "";
        // 希望連絡(メールが設定されている場合)
        if ($cntctWayMail == "1")
        {
            $strCntctWayStr = $strCntctWayStr . "メール,";
            $strCntctWayCd = "1";
        }
        else
        {
            $strCntctWayCd = "0";
        }
        // 希望連絡(TEL)が設定されている場合
        if ($cntctWayTel == "1")
        {
            $strCntctWayStr = $strCntctWayStr . "ＴＥＬ,";
            $strCntctWayCd = "1" . $strCntctWayCd;
        }
        else
        {
            $strCntctWayCd = "0" . $strCntctWayCd;
        }
        // 希望連絡(FAX)が設定されている場合
        if ($cntctWayFax == "1")
        {
            $strCntctWayStr = $strCntctWayStr . "ＦＡＸ,";
            $strCntctWayCd = $strCntctWayCd . "1";
        }
        else
        {
            $strCntctWayCd = $strCntctWayCd . "0";
        }
        // 希望連絡手段に値が入ってたら、最後のカンマを除去する
        if ($strCntctWayStr != "") $strCntctWayStr = rtrim($strCntctWayStr, ",");
        $this->_params['CntctWayStr'] = $strCntctWayStr;
        $this->_params['CntctWayCd'] = $strCntctWayCd;

        $inquiryTxtList = array();
        $strInquiryTxt = "";
        $inqryFlg = "";
        // 問合わせ内容1(条件に合う他の物件を紹介して欲しい)
        if (!empty($inquiry1))
        {
            $inquiryTxtList[1] = "条件に合う他の物件を紹介して欲しい";
            $inqryFlg = "1";
        }
        else
        {
            $inqryFlg = "0";
        }
        // 問合わせ内容2(その他)
        if (!empty($inquiry2))
        {
            $inquiryTxtList[2] = "その他";
            $inqryFlg = $inqryFlg . "1";
        }
        else
        {
            $inqryFlg = $inqryFlg . "0";
        }
        // // 問合わせ内容3(内見希望)
        // if (! empty ( $inquiry3 )) {
        // $inquiryTxtList [2] = "内見希望";
        // $inqryFlg = $inqryFlg . "1";
        // } else {
        // $inqryFlg = $inqryFlg . "0";
        // }
        // // 問合わせ内容4(類似の建物があれば紹介して欲しい)
        // if (! empty ( $inquiry4 )) {
        // $inquiryTxtList [4] = "類似の建物があれば紹介して欲しい";
        // $inqryFlg = $inqryFlg . "1";
        // } else {
        // $inqryFlg = $inqryFlg . "0";
        // }
        if ($this->m_isMobile == "0")
        {
            // PC
            $strInquiryTxt = "　" . implode("\r\n　", $inquiryTxtList);
        }
        else
        {
            // PC以外は並び変え
            ksort($inquiryTxtList);
            $strInquiryTxt = implode("\r\n", $inquiryTxtList);
            if (!empty($raitenDate))
            {
                // 日付
                $raitenTxt = "　希望来店日時:" . substr($raitenDate, 2, 2) . '/' . substr($raitenDate, 4, 2) . '/' . substr($raitenDate, 6, 2);
                // 時間
                $raitenTimeKbn = Array(
                    "1" => "午前",
                    "2" => "午後"
                );
                $raitenTimeTxt = $raitenTimeKbn[$raitenTime];
                if (!empty($raitenTimeTxt))
                {
                    $raitenTxt .= " " . $raitenTimeTxt;
                }
                // 希望連絡日時の追加
                $strInquiryTxt .= "\r\n" . $raitenTxt;
                // DB格納用
                $add_params['RaitenTxt'] = "\r\n" . $raitenTxt;
            }
            // $strInquiryTxt .= "\r\n";
        }
        $add_params['InquiryTxt'] = $strInquiryTxt;
        $add_params['InquiryFlg'] = $inqryFlg;

        $add_params['ComGenruFlg'] = $strLogGenruFlg;

        // 4固定(W21PAGE_VIEW_LOG.W21_KENSAKU_FLAG)
        $add_params['ViewKbn'] = "4";

        // W47REQUEST_KENSAKU_LOG登録用 Start
        $add_params['ReqData']['iYachinMin'] = $strTinryo1;
        $add_params['ReqData']['iYachinMax'] = $strTinryo2;
        $add_params['ReqData']['iKanrihiFlg'] = $strTinryo_jouken2;
        $add_params['ReqData']['iShikireiFlg'] = "";
        $add_params['ReqData']['sTatemonoType'] = $strSyubetuDB;
        $add_params['ReqData']['iEkitoho'] = $strEkitoho;
        $add_params['ReqData']['iSenyuMin'] = $strSenyu1;
        $add_params['ReqData']['iSenyuMax'] = $strSenyu2;
        $add_params['ReqData']['sMadori'] = $strMadoriDB;
        $add_params['ReqData']['iChikunensu'] = $strBuilt;
        $add_params['KodawariData']['vKodawari01'] = $strKodawariDB;
        $add_params['KodawariData']['vKodawari03'] = $strKodawariTypeDB;
        $add_params['ReqData']['iTyusyajyoKomi'] = $strTyusyajyo_komi;
        $add_params['ReqData']['iShikikinZero'] = $strShikikin_nashi;
        $add_params['ReqData']['iReikinZero'] = $strReikin_nashi;
        $add_params['ReqData']['iBasRiyou'] = $strBas_riyou;
        // W47REQUEST_KENSAKU_LOG登録用 End

        // メール送信用 Start
        $add_params['ShopName'] = $strP_shopnames;
        $add_params['TimeStr'] = $strTimeStr;
        $add_params['Kind'] = $strSrhType;
        // $add_params ['KindName'] = $strkindnameValue;
        $add_params['type'] = $strSyubetuValue;
        $add_params['Tinryo1'] = $strTinryo1Value;
        $add_params['Tinryo2'] = $strTinryo2Value;
        $add_params['Tinryonote'] = $strTinryoNotesValue;
        $add_params['Madori'] = $strMadoriValue;
        $add_params['Senyu'] = "（" . $strSenyu1Value . "から" . $strSenyu2Value . "）";
        $add_params['Built'] = $strBuiltValue;
        $add_params['Ekitoho'] = $strEkitohoValue;
        $add_params['Other'] = $strOtherNotesValue;

        // 名称（メール送信用）
        // まず、市区町村（沿線）単位に分割
        $strKindname2 = explode('/', $strKindname); // 名称

        foreach ($strKindname2 as $key2 => $val2)
        {
            // 町（駅）単位に分割
            $strKindname3 = explode(';', $val2); // 市区町村（沿線）単位名称

            foreach ($strKindname3 as $key3 => $val3)
            {
                $strKindnameValue .= $val3;
            }
        }
        $add_params['KindName'] = $strKindnameValue;
        // メール送信用 End

        // 建物詳細URL
        // $add_params ['TatemonoUrl'] = Apm_Config_Inquiry::URL_COM . "article/" . $add_params
        // ['OrgTatemonoCd'] . "/";

        $shopcode = explode(',', $strP_shopcds); // ショップコードを配列

        // --- メール判定 ---
        $this->setSendMailFlag($this->_params['Mail']);

        // ﾛｸﾞ情報格納処理 *****************************************
        try
        {
            // モデルの呼び出し
            $this->_model = new Inquiry_Model_Apiinquiry();
            $this->_model_bukken = new Inquiry_Model_Apibukken();

            // トランザクション開始
            $db = $this->_model->getDbConnection();
            $this->_model->startTransaction($db);

            // 問合わせID生成
            $this->m_strToiawaseId = strval($this->GetTimeString()) . strval($this->GetToiawaseSEQ($db));

            $add_params['InqNo'] = $this->m_strToiawaseId;

            // 問合せﾕｰｻﾞ情報格納ｸｴﾘ取得処理
            $resultw25 = $this->_model->insInqUserLog5($db, $this->_params, $add_params);

            // リクエスト検索情報ログ格納ｸｴﾘ取得処理 W47REQUEST_KENSAKU_LOG登録
            $resultw25 = $this->_model->requestKensakuLog2($db, $this->_params, $add_params);

            // // ﾍﾟｰｼﾞﾋﾞｭｰ情報登録（W21PAGE_VIEW_LOG）
            // $resultvlog = $this->_model->pageViewLog ( $db, $this->_params, $add_params );

            $shopVal = array();
            foreach ($shopcode as $key => $value)
            {
                // ﾍﾟｰｼﾞﾋﾞｭｰ情報登録（W21PAGE_VIEW_LOG）
                $value = trim($value);
                $shopVal[] = $value; // 20150126 Add
                $this->_params['ShopCd'] = $value;

                $resultvlog = $this->_model->pageViewLog($db, $this->_params, $add_params);
            }
            $this->_params['ShopCd'] = implode(",", $shopVal); // 20150126 Add

            // 問合せ店舗一覧取得ｸｴﾘ
                                                                // 店舗情報取得
            $shopList = $this->_model->getInqShopQry($this->_params, $db);

            // 20141222 S_Add
            // W33REQUEST_AREA_LOG登録
            $add_params['targetPrefCd'] = '';
            $add_params['targetCityCd'] = '';
            $add_params['targetTownCd'] = '';
            $add_params['targetRailCd'] = '';
            $add_params['targetStCd'] = '';
            if ($strSrhType == "1" || $strSrhType == "3")
            {
                // コード
                $strKindCd = explode(',', $strKindcode); // コードを配列に代入

                foreach ($strKindCd as $key => $val)
                {
                    // コードが５桁の場合（市区町村コードの場合）
                    if (strlen($val) == 5)
                    {
                        $add_params['Seqcount'] += 1;
                        $add_params['targetPrefCd'] = mb_substr($val, 0, 2);
                        $add_params['targetCityCd'] = mb_substr($val, 2, 3);
                        $resApi = $this->arraySum($resApi, $this->_model->InsRequestAreaLog($db, $this->_params, $add_params));
                    }
                    // コードが５桁の場合（町コードの場合）
                    else if (strlen($val) == 8)
                    {
                        $add_params['Seqcount'] += 1;
                        $add_params['targetPrefCd'] = mb_substr($val, 0, 2);
                        $add_params['targetCityCd'] = mb_substr($val, 2, 3);
                        $add_params['targetTownCd'] = mb_substr($val, 5, 3);
                        $resApi = $this->arraySum($resApi, $this->_model->InsRequestAreaLog($db, $this->_params, $add_params));
                    }
                }

                // if ($strTownCd != "") {
                // foreach ( $strTownCd as $key => $val ) {
                // // ﾘｸｴｽﾄｴﾘｱ情報格納ｸｴﾘ取得処理
                // $add_params ['Seqcount'] += 1;
                // $add_params ['targetPrefCd'] = mb_substr ( $val, 0, 2 );
                // $add_params ['targetCityCd'] = mb_substr ( $val, 2, 3 );
                // $add_params ['targetTownCd'] = mb_substr ( $val, 5, 3 );
                // $resApi = $this->arraySum ( $resApi, $this->_model->InsRequestAreaLog ( $db,
            // $this->_params, $add_params ) );
                // }
                // } else if ($strCityCd != "") {
                // foreach ( $strCityCd as $key => $val ) {
                // // ﾘｸｴｽﾄｴﾘｱ情報格納ｸｴﾘ取得処理
                // $add_params ['Seqcount'] += 1;
                // $add_params ['targetPrefCd'] = mb_substr ( $val, 0, 2 );
                // $add_params ['targetCityCd'] = mb_substr ( $val, 2, 3 );
                // $resApi = $this->arraySum ( $resApi, $this->_model->InsRequestAreaLog ( $db,
            // $this->_params, $add_params ) );
                // }
                // } else if ($strPrefCd != "") {
                // foreach ( $strPrefCd as $key => $val ) {
                // // ﾘｸｴｽﾄｴﾘｱ情報格納ｸｴﾘ取得処理
                // $add_params ['Seqcount'] += 1;
                // $add_params ['targetPrefCd'] = mb_substr ( $val, 0, 2 );
                // $resApi = $this->arraySum ( $resApi, $this->_model->InsRequestAreaLog ( $db,
            // $this->_params, $add_params ) );
                // }
                // }
            }
            else if ($strSrhType == "2")
            {
                // 駅コード
                $strStCd = explode(',', $strKindcode); // コードを配列

                if ($strStCd != "")
                {
                    foreach ($strStCd as $key => $val)
                    {
                        // ﾘｸｴｽﾄｴﾘｱ情報格納ｸｴﾘ取得処理
                        $add_params['Seqcount'] += 1;
                        $add_params['targetRailCd'] = mb_substr($val, 0, 4);
                        $add_params['targetStCd'] = $val;
                        $resApi = $this->arraySum($resApi, $this->_model->InsRequestAreaLog($db, $this->_params, $add_params));
                    }
                }
                else if ($strRailCd != "")
                {
                    foreach ($strRailCd as $key => $val)
                    {
                        // ﾘｸｴｽﾄｴﾘｱ情報格納ｸｴﾘ取得処理
                        $add_params['Seqcount'] += 1;
                        $add_params['targetRailCd'] = $val;
                        $resApi = $this->arraySum($resApi, $this->_model->InsRequestAreaLog($db, $this->_params, $add_params));
                    }
                }
            }
            // 20141222 E_Add

            // --- あげちゃいますキャンペーン初期化 ---
            $this->MakeCampaignAgechau($this->_params["CampaignAgechau"]);

            // =====キャンペーン反響テーブルカウント(あげちゃいます)=====
            foreach ($this->m_arrCampaignAgechau as $key => $value)
            {
                $this->UpdLettersCampaign($db, $value["M94_CAMPAIGN_KBN"], $value["M94_CAMPAIGN_CD"], 2, $arrBukken);
            }

            // あげちゃいますキャンペーンはDBからデータ取得
            // お宝の表示は行わない
            $add_params['strDownloadUrl'] = "";
            $add_params['campaign'] = "";
            foreach ($this->m_arrCampaignAgechauAll as $campaignAll)
            {
                if (array_key_exists($campaignAll["M94_CAMPAIGN_CD"], $this->m_arrCampaignAgechau))
                {
                    if ($campaignAll["M94_CAMPAIGN_CD"] != "17")
                    {
                        $add_params['campaign'] .= "＜" . $campaignAll["M94_CAMPAIGN_NAME"] . "＞　応募する\n";
                    }
                    else
                    {
                        $add_params['campaign'] .= "＜" . $campaignAll["M94_CAMPAIGN_NAME"] . "＞　希望する\n";
                    }
                    $add_params['campaign_str'] .= "　　　◆◆◆" . $campaignAll["M94_CAMPAIGN_NAME"] . "◆◆◆に、応募\n";
                }
                // else
                // {
                // if($campaignAll["M94_CAMPAIGN_CD"] <> "17"){
                // $add_params['campaign'] .= "＜" . $campaignAll["M94_CAMPAIGN_NAME"] . "＞　応募しない\n";
                // }
                // else{
                // $add_params['campaign'] .= "＜" . $campaignAll["M94_CAMPAIGN_NAME"] . "＞　希望しない\n";
                // }
                // }

                // アパマン48キャンペーン期間か
                if ($campaignAll["M94_CAMPAIGN_CD"] == Apm_Config_Inquiry::AKB_CAMPAIGN_CD)
                {
                    // =====キャンペーンダウンロード管理登録
                    $this->m_insW25CampaignDownloadMngCnt += $this->_model_bukken->InsCampaignDownload($db, $this->m_strToiawaseId, $campaignAll["ACCESS_KEY"]);

                    $add_params['isMobile'] = $this->m_isMobile;
                    $add_params['strApaman48DownloadUrl'] = $this->_config['apm']['baseurl'] . "AKB48/cp/download?id=" . $this->m_strToiawaseId . "&key=" . $campaignAll["ACCESS_KEY"];
                }
                // =====キャンペーンダウンロード管理
                if ($campaignAll["M94_CAMPAIGN_CD"] == Apm_Config_Inquiry::EXILE_CAMPAIGN_CD)
                {
                    // DB登録
                    $this->m_insW25CampaignDownloadMngCnt += $this->_model_bukken->InsExileCampaignDownload($db, $this->m_strToiawaseId, $this->m_isMobile, $campaignAll["ACCESS_KEY"]);
                    // URI生成
                    if ($this->m_isMobile == "0")
                    {
                        // PC
                        $strExileDownloadUrl = $this->_config['apm']['baseurl'] . "exile/cp/download?id=" . $this->m_strToiawaseId . "&key=" . $campaignAll["ACCESS_KEY"];
                    }
                    else if ($this->m_isMobile == "1")
                    {
                        // mobile
                        $strExileDownloadUrl = $this->_config['apm']['baseurl'] . "mobile/exile/download?id=" . $this->m_strToiawaseId . "&key=" . $campaignAll["ACCESS_KEY"];
                    }
                    else
                    {
                        // SP
                        $strExileDownloadUrl = $this->_config['apm']['baseurl'] . "exile/cp/download/sp?id=" . $this->m_strToiawaseId . "&kbn=" . $this->m_isMobile . "&key=" . $campaignAll["ACCESS_KEY"];
                    }
                    // メールMSG生成
                    $strDownloadMsg = "";
                    if ($this->m_isMobile == "0")
                    {
                        // PC
                        $strDownloadMsg .= "■スクリーンセーバーダウンロード\n";
                        $strDownloadMsg .= "現在、APAMANxEXILEキャンペーン中につき、お問合わせいただいた方全員に\n";
                        $strDownloadMsg .= "もれなくAPAMANxEXILEオリジナルスクリーンセーバーを差し上げています。\n";
                        $strDownloadMsg .= "下記、URLからダウンロードしてお楽しみください。\n";
                        $strDownloadMsg .= "※ダウンロードは3回までとなっておりますのでご注意ください。\n";
                    }
                    else
                    {
                        $strDownloadMsg .= "■壁紙ダウンロード\n";
                        $strDownloadMsg .= "現在、APAMANxEXILEキャンペーン中につき、お問合わせいただいた方全員に\n";
                        $strDownloadMsg .= "もれなくAPAMANxEXILEオリジナル壁紙を差し上げています。\n";
                        $strDownloadMsg .= "下記、URLからダウンロードしてお楽しみください。\n";
                    }
                    $strDownloadMsg .= " \n";
                    $strDownloadMsg .= $strExileDownloadUrl . "\n";

                    $add_params['strDownloadUrl'] .= $strDownloadMsg;
                }
            }

            // INSERT START　リクエスト・店舗問い合わせログの記録 2011/09/26 ss-sakakibara
            // =====ログ情報保存=====
            if ($this->isLogIns())
            {
                // W26TOIAWASE_TENPO登録
                foreach ($shopcode as $key => $value)
                {
                    $value = trim($value);
                    $this->_model->InsInqTenpoLog($this->m_strToiawaseId, $value, $db);
                }
                // $this->_model->InsInqTenpoLog ( $this->m_strToiawaseId, $this->_params
            // ['ShopCd'], $db );
            }
            // INSERT END　リクエスト・店舗問い合わせログの記録 2011/09/26 ss-sakakibara

            // ﾒｰﾙ送信処理 ********************************************
            // foreach ($shopList as $val){
            // $result = $this->SendMailMain ( $mail, array_merge ( $add_params, $shopList ), $db
            // );// 20150126
            $result = $this->SendMailMain($mail, array_merge($add_params, $shopList[0]), $shopList, $add_params, $db);

            if ($result == "0")
            {
                $this->raiseError('メール送信エラー');
            }
            // }

            __log_debug(__FILE__, __LINE__, __METHOD__, "コミットします");
            $this->_model->commitTransaction($db);
            $db->closeConnection();

            $result = 1;
        }
        catch (Exception $e)
        {
            // エラー発生時
            __log_debug(__FILE__, __LINE__, __METHOD__, "ロールバックします");
            $this->_model->rollbackTransaction($db);
            $db->closeConnection();
            $result = 0;
        }
        // 返却データ作成
        $detailArr = array();
        array_push($detailArr, $resultw25, $resultvlog);

        $resResult = array(
            'api_result' => array(
                'result' => $result,
                'res_detail' => $detailArr
            )
        );
        $resResult['CV_ToiawaseId'] = $this->m_strToiawaseId;
        // 返却処理
        $this->_api_data = $resResult;
        $this->display();
    }
    // private function SendMailMain($mail, $addinfo, $db = "") {// 20150126
    private function SendMailMain($mail, $addinfo, $shopList, $basicInfo, $db = "")
    {
        // ｽﾃｰﾀｽ初期化
        $status = false;

        $userResult = 1;
        $shopResult = 1;
        $officeResult = 1;
        $aosshopResult = 1;
        $mailResult = 1;

        // ﾕｰｻﾞのﾒｰﾙｱﾄﾞﾚｽが設定されている場合はユーザへメール送信
        if ($mail != "")
        {
            $userResult = $this->SendMailUser($mail, $addinfo);
        }

        // 店舗へのメール送信
        // 店舗のﾒｰﾙｱﾄﾞﾚｽが設定されている場合
        if ($addinfo['M05_TENPO_MAIL'] != "")
        {

            // 20150126 S_Add
            $count = 0;
            foreach ($shopList as $val)
            {
                // メール送信処理 for 店舗 and 本部
                // $shopResult = $this->SendMailShop ( $mail, $val );
                $shopResult = $this->SendMailShop($mail, array_merge($addinfo, $val));

                $officeResult = $this->SendMailOffice($mail, array_merge($addinfo, $val));
            }
            // 20150126 E_Add

            // メール送信処理 for 本部
            // $officeResult = $this->SendMailOffice ( $mail, $addinfo );

            // if ($this->isAosShop ( $addinfo ['M05_TENPO_CD'], $db ) == true) {
            // // メール送信処理 for ＡＯＳ店舗
            // $aosshopResult = $this->SendMailAosShop ( $mail, $addinfo );
            // }
        }
        else
        {
            // 店舗のメールアドレスが設定されていない場合
            // ﾒｰﾙ送信処理(ﾒｰﾙｱﾄﾞﾚｽ未設定時)
            $mailResult = $this->SendMailNoMail($mail, $addinfo);
        }

        $result = 1;
        if ($userResult == 0 || $shopResult == 0 || $officeResult == 0 || $aosshopResult == 0 || $mailResult == 0)
        {
            $result = 0;
        }
        return $result;
    }

    // 問い合わせユーザへのメール送信
    private function SendMailUser($mail, $addinfo)
    {
        // from(送信元)、to（あて先)
        $strMailTo = array(
            $mail => ""
        );
        $strMailFrom = array(
            Apm_Config_Mail::MAIL_NETWORK => ""
        );
        $strMailReply = array(
            Apm_Config_Mail::MAIL_LATE => ""
        );

        // メール本文に必要なパラメータ
        $mail_params[Apm_Otheritems::SEND_MAIL_EX_SUBJECT_KEY] = "［アパマンショップ］検索条件でのお問い合わせのご確認";
        $mail_params[Apm_Otheritems::SEND_MAIL_EX_TO_KEY] = $strMailTo;
        $mail_params[Apm_Otheritems::SEND_MAIL_EX_FROM_KEY] = $strMailFrom;
        $mail_params[Apm_Otheritems::SEND_MAIL_EX_REPLY_TO_KEY] = $strMailReply;

        // テンプレート選択
        $strMailTmp = "";
        if ($this->m_isMobile == "1")
        {
            // mobile
            $strMailTmp = "MailConditionsUserMobile.tpl";
        }
        else
        {
            // 他
            $strMailTmp = "MailConditionsUser.tpl";
        }

        // ﾒｰﾙ送信処理
        $result = $this->sendToiawaseMailJudge($strMailTmp, array_merge($this->_params, $addinfo), $mail_params, 3);
        // if($this->isSendUser() == true) {
        // $result = $this->sendToiawaseMail($strMailTmp, array_merge($this->_params,$addinfo),
        // $mail_params);
        // }

        return $result;
    }

    // 店舗へのメール送信
    private function SendMailShop($mail, $addinfo)
    {
        $strSubject = "■アパマンショップ・検索条件のお問い合わせメール";
        // キャリア付加
        if (!empty($this->m_carrier))
        {
            $strSubject .= "＜{$this->m_carrier}版＞";
        }
        $strMailFrom = array(
            Apm_Config_Mail::MAIL_NETWORK => ""
        ); // 送信元ﾒｰﾙｱﾄﾞﾚｽ
        $strMailTo = array(
            $addinfo['M05_TENPO_MAIL'] => ""
        ); // 送信先ﾒｰﾙｱﾄﾞﾚｽ
        $strMailReply = array(
            $mail => ""
        );
        $strMailCc = array();
        // 特定アドレスのCC追加
        $cc_list = Apm_Config_Inquiry::$SHOP_MAIL_CC_SHOP[$addinfo['M05_TENPO_CD']];
        if (!empty($cc_list) && is_array($cc_list))
        {
            foreach ($cc_list as $ccMail)
            {
                $strMailCc[$ccMail] = "";
            }
        }

        // @ 送信先ﾒｰﾙｱﾄﾞﾚｽ
        // 本文の設定
        $mail_params[Apm_Otheritems::SEND_MAIL_EX_SUBJECT_KEY] = $strSubject;
        $mail_params[Apm_Otheritems::SEND_MAIL_EX_TO_KEY] = $strMailTo;
        $mail_params[Apm_Otheritems::SEND_MAIL_EX_FROM_KEY] = $strMailFrom;
        if ($mail != "")
        {
            $mail_params[Apm_Otheritems::SEND_MAIL_EX_REPLY_TO_KEY] = $strMailReply;
        }
        if (count($strMailCc) > 0)
        {
            $mail_params[Apm_Otheritems::SEND_MAIL_EX_CC_KEY] = $strMailCc;
        }

        // メール制御ロジック
        $result = $this->sendToiawaseMailJudge("MailConditionsShop.tpl", array_merge($this->_params, $addinfo), $mail_params, 2);
        // if($this->isSendShop() == true) {
        // // ﾒｰﾙ送信処理
        // $result =
        // $this->sendToiawaseMail("MailShopShop.tpl",array_merge($this->_params,$addinfo),
        // $mail_params);
        // }else if($this->getReplaceShopMail() != "") {
        // $mail_params[Apm_Otheritems::SEND_MAIL_EX_TO_KEY] = array($this->getReplaceShopMail() =>
        // "");
        // if ($mail != "") {
        // $mail_params[Apm_Otheritems::SEND_MAIL_EX_REPLY_TO_KEY] =
        // array($this->getReplaceShopMail() => "");
        // }
        // // ﾒｰﾙ送信処理
        // $result =
        // $this->sendToiawaseMail("MailShopShop.tpl",array_merge($this->_params,$addinfo),
        // $mail_params);
        // }

        return $result;
    }

    // 本部へのメール送信
    private function SendMailOffice($mail, $addinfo)
    {
        $strSubject = "■アパマンショップ・検索条件のお問い合わせメール";
        // キャリア付加
        if (!empty($this->m_carrier))
        {
            $strSubject .= "＜{$this->m_carrier}版＞";
        }
        $strSubject .= "(" . $addinfo['M05_TENPO_NAME'] . ")";
        $strMailFrom = array(
            Apm_Config_Mail::MAIL_NETWORK => ""
        ); // 送信元ﾒｰﾙｱﾄﾞﾚｽ
        $strMailTo = array(
            Apm_Config_Mail::MAIL_NETWORK => ""
        ); // 送信先ﾒｰﾙｱﾄﾞﾚｽ
        $strMailReply = array(
            $mail => ""
        );

        // @ 送信先ﾒｰﾙｱﾄﾞﾚｽ
        // 本文の設定
        $mail_params[Apm_Otheritems::SEND_MAIL_EX_SUBJECT_KEY] = $strSubject;
        $mail_params[Apm_Otheritems::SEND_MAIL_EX_TO_KEY] = $strMailTo;
        $mail_params[Apm_Otheritems::SEND_MAIL_EX_FROM_KEY] = $strMailFrom;
        if ($mail != "")
        {
            $mail_params[Apm_Otheritems::SEND_MAIL_EX_REPLY_TO_KEY] = $strMailReply;
        }

        $result = $this->sendToiawaseMailJudge("MailConditionsHonbu.tpl", array_merge($this->_params, $addinfo), $mail_params, 1);
        // if($this->isSendHonbu() == true) {
        // // ﾒｰﾙ送信処理
        // $result =
        // $this->sendToiawaseMail("MailShopHonbu.tpl",array_merge($this->_params,$addinfo),
        // $mail_params);
        // }else if($this->getReplaceHonbuMail() != "") {
        // $mail_params[Apm_Otheritems::SEND_MAIL_EX_TO_KEY] = array($this->getReplaceHonbuMail() =>
        // "");
        // if ($mail != "") {
        // $mail_params[Apm_Otheritems::SEND_MAIL_EX_REPLY_TO_KEY] =
        // array($this->getReplaceHonbuMail() => "");
        // }
        // // ﾒｰﾙ送信処理
        // $result =
        // $this->sendToiawaseMail("MailShopHonbu.tpl",array_merge($this->_params,$addinfo),
        // $mail_params);
        // }

        return $result;
    }

    // AOS店舗へのメール送信
    private function SendMailAosShop($mail, $addinfo)
    {
        $strSubject = "■アパマンショップ・検索条件のお問い合わせメール";
        // キャリア付加
        if (!empty($this->m_carrier))
        {
            $strSubject .= "＜{$this->m_carrier}版＞";
        }
        $strMailFrom = array(
            Apm_Config_Mail::MAIL_NETWORK => ""
        ); // 送信元ﾒｰﾙｱﾄﾞﾚｽ
        $strMailTo = array(
            "aos_" . $addinfo['M05_TENPO_NO'] . "@apamanshop.co.jp" => ""
        ); // 送信先ﾒｰﾙｱﾄﾞﾚｽ

        // @ 送信先ﾒｰﾙｱﾄﾞﾚｽ
           // 本文の設定
        $mail_params[Apm_Otheritems::SEND_MAIL_EX_SUBJECT_KEY] = $strSubject;
        $mail_params[Apm_Otheritems::SEND_MAIL_EX_TO_KEY] = $strMailTo;
        $mail_params[Apm_Otheritems::SEND_MAIL_EX_FROM_KEY] = $strMailFrom;

        $result = $this->sendToiawaseMailJudge("MailConditionsAosShop.tpl", array_merge($this->_params, $addinfo), $mail_params, 2);
        // if($this->isSendHonbu() == true) {
        // // ﾒｰﾙ送信処理
        // $result =
        // $this->sendToiawaseMail("MailShopAosShop.tpl",array_merge($this->_params,$addinfo),
        // $mail_params);
        // }else if($this->getReplaceHonbuMail() != "") {
        // $mail_params[Apm_Otheritems::SEND_MAIL_EX_TO_KEY] = array($this->getReplaceHonbuMail() =>
        // "");
        // // ﾒｰﾙ送信処理
        // $result =
        // $this->sendToiawaseMail("MailShopAosShop.tpl",array_merge($this->_params,$addinfo),
        // $mail_params);
        // }

        return $result;
    }

    // 問い合わせメールエラー
    private function SendMailNoMail($mail, $addinfo)
    {
        $strSubject = "問い合わせメールエラー（検索条件のお問い合わせ）";
        $strMailFrom = array(
            Apm_Config_Mail::MAIL_NETWORK => ""
        ); // 送信元ﾒｰﾙｱﾄﾞﾚｽ
        $strMailTo = array(
            Apm_Config_Mail::MAIL_NETWORK => ""
        ); // 送信先ﾒｰﾙｱﾄﾞﾚｽ

        // @ 送信先ﾒｰﾙｱﾄﾞﾚｽ
           // 本文の設定
        $mail_params[Apm_Otheritems::SEND_MAIL_EX_SUBJECT_KEY] = $strSubject;
        $mail_params[Apm_Otheritems::SEND_MAIL_EX_TO_KEY] = $strMailTo;
        $mail_params[Apm_Otheritems::SEND_MAIL_EX_FROM_KEY] = $strMailFrom;

        $result = $this->sendToiawaseMailJudge("MailConditionsError.tpl", array_merge($this->_params, $addinfo), $mail_params, 1);
        // if($this->isSendHonbu() == true) {
        // // ﾒｰﾙ送信処理
        // $result =
        // $this->sendToiawaseMail("MailShopError.tpl",array_merge($this->_params,$addinfo),
        // $mail_params);
        // }else if($this->getReplaceHonbuMail() != "") {
        // $mail_params[Apm_Otheritems::SEND_MAIL_EX_TO_KEY] = array($this->getReplaceHonbuMail() =>
        // "");
        // // ﾒｰﾙ送信処理
        // $result =
        // $this->sendToiawaseMail("MailShopError.tpl",array_merge($this->_params,$addinfo),
        // $mail_params);
        // }

        return $result;
    }

    /**
     * あげちゃいますキャンペーン情報を作成する
     * 下記変数の初期化
     * $m_arrCampaignAgechauAll
     * $m_arrCampaignAgechau
     * $m_arrCampaignAgechauTakara
     */
    private function MakeCampaignAgechau($strCampaignParam)
    {
        // 一旦初期化
        $this->m_arrCampaignAgechauAll = array();
        $this->m_arrCampaignAgechau = array();
        $this->m_arrCampaignAgechauTakara = array();
        $this->m_arrCampaignHeya = array();

        $arrSelectCampaign;
        $arrCampaignInfo;

        $arrTakara;

        $campaign;
        $takara;

        // 対象AKBキャンペーン取得
        $this->m_arrCampaignAgechauAll = $this->_model_bukken->GetCampaignEx("2, 4", 2, $this->m_isMobile);

        if (!Apm_Otheritems::IsNullOrEmpty($strCampaignParam))
        {
            // キャンペーン毎に分割
            if (strpos($strCampaignParam, self::DELIM_CAMPAIGN) === false)
            {
                $arrSelectCampaign = array(
                    str_replace(" ", "", $strCampaignParam)
                );
            }
            else
            {
                $arrSelectCampaign = split(self::DELIM_CAMPAIGN, str_replace(" ", "", $strCampaignParam));
            }

            for ($i = 0; $i < count($arrSelectCampaign); $i++)
            {
                $arrTakara = array();
                $campaign = null;
                $takara = null;

                // キャンペーンとお宝を分割
                if (strpos($arrSelectCampaign[$i], self::DELIM_OTAKARA) === false)
                {
                    $arrCampaignInfo = array(
                        str_replace(" ", "", $arrSelectCampaign[$i])
                    );
                }
                else
                {
                    $arrCampaignInfo = split(self::DELIM_OTAKARA, str_replace(" ", "", $arrSelectCampaign[$i]));
                }

                for ($j = 0; $j < count($arrCampaignInfo); $j++)
                {
                    if ($j == 0)
                    {
                        // 先頭はキャンペーンコード
                        // キャンペーン情報取得

                        $campaign = $this->_model_bukken->GetCampaign("2, 4", $arrCampaignInfo[$j], $this->m_isMobile);
                        if (count($campaign) == 0)
                        {
                            // 万一取得できなかった場合はnullにして抜ける
                            __log_debug(__FILE__, __LINE__, __METHOD__, $arrCampaignInfo[$j] . "のキャンペーンコードはありません");
                            $campaign = null;
                            break;
                        }
                    }
                    else
                    {
                        // ２番目以降はお宝コード
                        $takara = $this->_model_bukken->GetCampaignTakara($campaign[0]["M94_CAMPAIGN_CD"], $arrCampaignInfo[$j]);
                        if (count($takara) > 0)
                        {
                            // 万一取得できなかった場合はnullにして抜ける
                            __log_debug(__FILE__, __LINE__, __METHOD__, $campaign[0]["M94_CAMPAIGN_CD"] . "のキャンペーンコードの" . $arrCampaignInfo[$j] . "の宝はありません");
                            $campaign = null;
                            break;
                        }
                        $arrTakara[$arrCampaignInfo[$j]] = $takara[0];
                    }
                }
                if (!is_null($campaign))
                {
                    $this->m_arrCampaignAgechau[$campaign[0]["M94_CAMPAIGN_CD"]] = $campaign[0];
                    $this->m_arrCampaignAgechauTakara[$campaign[0]["M94_CAMPAIGN_CD"]] = $arrTakara;
                }
            }
        }
    }

    /**
     * キャンペーン反響数テーブル更新
     *
     * @param connection $db
     *            DBコネクション
     * @param int $intCampaignKbn
     *            キャンペーン区分
     * @param int $intCampaignCd
     *            キャンペーンコード
     * @param int $intToiawaseKbn
     *            問い合わせ区分
     * @param array $arrBukken
     *            物件データ（部屋付きキャンペーンのみ）
     */
    private function UpdLettersCampaign($db, $intCampaignKbn, $intCampaignCd, $intToiawaseKbn, $arrBukken = array())
    {
        $arrLetterCampaign;

        $ymd = date("Ymd");
        $device = $this->m_isMobile;

        // モデル生成
        // $this->_model_bukken = new Inquiry_Model_Apibukken();

        $db_2 = $this->_model_bukken->getDbConnection();
        $this->_model_bukken->startTransaction($db_2);

        try
        {
            $arrLetterCampaign = $this->_model_bukken->GetLettersCampaign($db_2, $intCampaignKbn, $ymd, $intCampaignCd, $device, $intToiawaseKbn, 2);

            if (count($arrLetterCampaign) == 0)
            {
                $this->m_insupdW75LettersCampaignCnt += $this->_model_bukken->InsLettersCampaign($db_2, $intCampaignKbn, $ymd, $intCampaignCd, $device, $intToiawaseKbn, 2);
            }
            else
            {
                $this->m_insupdW75LettersCampaignCnt += $this->_model_bukken->UpdLettersCampaign($db_2, $intCampaignKbn, $ymd, $intCampaignCd, $device, $intToiawaseKbn, 2);
            }

            // キャンペーン応募状況を登録
            $this->m_insW76ApplyCampaignCnt += $this->_model_bukken->InsApplyCampaign($db_2, $intCampaignCd, $intToiawaseKbn, $this->m_strToiawaseId, $intCampaignKbn, $device, $arrBukken);

            $this->_model_bukken->commitTransaction($db_2);
            __log_debug(__FILE__, __LINE__, __METHOD__, "コミットしました");
            $db_2->closeConnection();
        }
        catch (Exception $e)
        {
            $this->_model_bukken->rollbackTransaction($db_2);
            __log_debug(__FILE__, __LINE__, __METHOD__, "ロールバックしました");
            $db_2->closeConnection();
            throw $e;
        }
    }

}
?>
